package com.code.day08;

/**
 * @author wxvirus
 */
public class Demo01BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
        int key = 11;

        int index = binarySearch(arr);
        System.out.println("index = " + index);
        System.out.println("arr[index] = " + arr[index]);
    }

    private static int binarySearch(int[] arr) {
        int min = 0;
        int max = arr.length - 1;
        // 定义一个mid代表中间索引
        int mid = 0;
        // 定义一个key代表要查询的元素
        int key = 11;

        while (min <= max) {
            mid = (min + max) / 2;
            if (arr[mid] < key) {
                min = mid + 1;
            } else if (arr[mid] > key) {
                max = mid - 1;
            } else {
                System.out.println("找到了，索引为：" + mid);
                return mid;
            }
        }
        // 代表的是找不到
        return -1;
    }
}
